const WebSocket = require("ws"); // 引入模块
const ws = new WebSocket.Server({ port: 8080 }, () => {
  // 监听接口
  console.log("socket start");
});

var i = 1;
var timer;
var start = (client) => {
  console.log("start");
  timer = setInterval(() => {
    client.send(i);
    i++;
  }, 1000);
};
var stop = () => {
  clearInterval(timer);
  // setTimeout(start,2000) //重启
};
var restart = (client) => {
  i = 1;
  start(client);
};
let clients = [];

const msg = [
  {
    identification: 292,
    isUsed: false,
    synchroTime: "2019-10-09T08:44:01Z",
    number: "22Y1910090004",
  },
  {
    identification: 293,
    isUsed: false,
    synchroTime: "2019-10-09T08:44:01Z",
    number: "22Y1910090005",
  },
  {
    identification: 294,
    isUsed: false,
    synchroTime: "2019-10-09T08:44:01Z",
    number: "22Y1910090006",
  },
];

ws.on("connection", (client) => {
  clients.push(client);
  clients.push(msg);
  client.on("message", (msg) => {
    console.log("客户端：", msg);
    switch (msg) {
      case "开始接收socket信息":
        start(client);
        break;
      case "停止接收socket信息":
        stop();
        break;
      case "重新接收socket信息":
        stop();
        restart(client);
        break;
      case "不再接收socket信息":
        stop();
        i = 1;
        break;
    }
  });
  client.on("close", (msg) => {
    console.log("关闭服务器连接");
  });
});
